<?php 
/***********************************************strat交易API***************************************************/ 
	/**
	 *	taobao.trades.bought.get:搜索当前会话用户作为买家达成的交易记录 [买]
	 *  与淘宝网我的淘宝中的“已买到的宝贝”功能一致   
	 * */
 	function TOP_TradesBoughtGet($userParamArr){
 		$client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,tradesBoughtGet,'trade');  
	 }
	/**
	 *	taobao.trades.sold.get:搜索当前会话用户作为卖家已卖出的交易数据 [买]
	 *  与淘宝网我的淘宝中的“已卖出的宝贝”功能一致   
	 * */
 	function TOP_TradesSoldGet($userParamArr){
 		$client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,tradesSoldGet,'trade');  
 	}
 	/**
	 *	taobao.trades.sold.increment.get:搜索当前会话用户作为卖家已卖出的增量交易数据  [高]
	 *  与淘宝网我的淘宝中的“已卖出的宝贝”功能一致, 只能查询时间跨度为一天的交易记录   性能高  
	 * */
 	function TOP_TradesSoldIncrementGet($userParamArr){
	 		$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,tradesSoldIncrementGet,'trade'); 
 	}
	/**
	 *	taobao.trade.get:获取单笔交易的部分信息(性能高)   [买]
	 *  获取到的详细信息中不包含姓名，邮件，电话或手机，和支付宝账号信息   
	 * */
 	function TOP_TradeGet($userParamArr){
	 		$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,tradeGet);  
 	}
 	/**
	 *	taobao.trade.fullinfo.get:获取单笔交易的详细信息   [商]
	 *    
	 * */
	function TOP_TradeFullinfoGet($userParamArr){
			$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,tradeFullinfoGet);  
	 } 
	/**
	 *	taobao.trade.close:卖家关闭一笔交易     [高]
	 *    
	 * */
    function TOP_TradeClose($userParamArr){
    		$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,tradeClose);  
 	}
	/**
	 *	taobao.trade.memo.add:添加一笔登录用户为买家或卖家的备注 [商]
	 *    
	 * */
 	function TOP_TradeMemoAdd($userParamArr){
 		   	$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,tradeMemoAdd); 
 	} 
    /**
	 *	taobao.trade.memo.update:修改一笔登录用户为买家或卖家的备注  [商]
	 *    
	 * */
	function TOP_TradeMemoUpdate($userParamArr){
		 	$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,tradeMemoUpdate);  
 	} 
    /**
	 *	taobao.refunds.apply.get:查询买家申请的退款列表    [专] 
	 * */
 	function TOP_RefundsApplyGet($userParamArr){
	 		$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,refundsApplyGet,'refund');  
 	} 
    /**
	 *	taobao.refunds.receive.get:查询卖家收到的退款列表  [专] 
	 * */
 	function TOP_RefundsReceiveGet($userParamArr){
 			$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,refundsReceiveGet,'refund');  
	 }
	/**
	 *	taobao.refund.get:查询单笔退款详情   [专] 
	 * */
 	function TOP_RefundGet($userParamArr){
 			$client = new Client();  
		    setUserParameter($client,$userParamArr);  
		    return returnCallBackPage($client,refundGet);  
 	} 
	/**
	 *	taobao.trade.confirmfee.get:获取交易确认收货费用  [高]
	 *    
	 * */ 
 	function TOP_TradesConfirmfeeGet($userParamArr){
 	
	 } 
	/**
	 *	taobao.refund.message.add :创建退款留言/凭证   [专]
	 *    
	 * */
 	function TOP_RefundMessageAdd(){
 	
	 }
	/**
	 *	taobao.refund.messages.get :退款留言/凭证列表查询  [专]
	 *    
	 * */
 	function TOP_RefundMessagesGet( $userParamArr ){
		$client = new Client();  
		setUserParameter($client,$userParamArr);  
		return returnCallBackPage($client,refundMessagesGet,'refundMessage');  
	} 
	/**
	 *	taobao.trade.snapshot.get:交易快照查询    [高]
	 *    
	 * */
 	function TOP_TradeSnapshotGet(){
 	
   }
 
 
/*************************************************end交易API***************************************************/ 
  	/**
  	 * 查询买家申请的退款列表  taobao.refunds.apply.get
  	 * 
  	 * */
	function GetRefundsApply(){ 
			$userParamArr = array(
						'fields' => "refund_id,tid,title,buyer_nick,seller_nick,total_fee,status,created,refund_fee",
						'status'  =>'WAIT_SELLER_AGREE',
						'type'    => 'guarantee_trade',
						'page_no'  =>1,
						'page_size' =>40,
					);  
			 return TOP_RefundsApplyGet($userParamArr);  		  
	} 
    /**
  	 *  taobao.refunds.receive.get:查询卖家收到的退款列表  [专] 
  	 *  GetRefundsReceive('SELLER_REFUSE_BUYER;WAIT_SELLER_AGREE;WAIT_BUYER_RETURN_GOODS')
  	 * */
	function GetRefundsReceive($status){ 
		 	$status_keys = explode(';',$status);  
		 	$result = array(
		 					'recordCounts' => 0,
		 					'list'       =>array(),
		 				  );   
		 	foreach ($status_keys as $stats){  //只下载选中了的状态标志位 
		    			 if(!$stats) continue;
   						 $userParamArr = array(
											'fields' => "refund_id, tid, title, buyer_nick, seller_nick, total_fee, status, created, refund_fee, oid, good_status, company_name, sid, payment, reason, desc, has_good_return, modified, order_status ",
											'status'  => $stats , 
											//'SELLER_REFUSE_BUYER',//WAIT_SELLER_AGREE(买家已经申请退款，等待卖家同意) WAIT_BUYER_RETURN_GOODS(卖家已经同意退款，等待买家退货)WAIT_SELLER_CONFIRM_GOODS(买家已经退货，等待卖家确认收货) SELLER_REFUSE_BUYER(卖家拒绝退款)  CLOSED(退款关闭) SUCCESS(退款成功)  
											'type'     => 'guarantee_trade',
											'page_no'  => 1,
											'page_size' =>40,
										);  
					     $result_t = TOP_RefundsReceiveGet($userParamArr); 
					     $result['recordCounts'] = $result['recordCounts'] + $result_t['recordCounts'] ;  
					     $result['list'] = $result['list'] + $result_t['list'] ;  
   			}  
			return $result;  		  
	} 
    /**
	 * taobao.refund.get:查询单笔退款详情   [专] 
	 * */
	function GetArrRefundGet( $refund_id ){
		$userParamArr = array(
						'fields' => 'refund_id, alipay_no, tid, oid, buyer_nick, seller_nick, total_fee, status, created, refund_fee, good_status, has_good_return, payment, reason, desc, iid, title, price, num, good_return_time, company_name, sid, address, shipping_type, refund_remind_timeout ',
						'refund_id' =>  $refund_id
					);      
	    $result = TOP_RefundGet($userParamArr);
	    $result['refund_desc'] = $result['desc'];  
	    OS_InsertIntoTB('tb_refund','refund_id',$result['refund']);   //写退单主表 退款结构 
	    $result['refund']['refund_remind_timeout']['refund_id']=$result['refund']['refund_id'] ;  
	    OS_InsertIntoTB('tb_refundremindtimeout','refund_id', $result['refund']['refund_remind_timeout'] );     //退款超时结构  
  	    GetRefundMessages( $refund_id );  //留言/凭证数据结构  
	    echo ($refund_id.'退单下载成功 <a href="#" onclick="history.go(-1)">返回</a>');  
	} 
	/**
	 * 留言/凭证数据结构    [专] 
	 * */
	function GetRefundMessages( $refund_id ){
		$userParamArr = array(
							'fields'    => 'id,refund_id,owner_id,owner_nick,owner_role,content,pic_urls,created',
							'refund_id' =>$refund_id, 
						);   			
		$result = TOP_RefundMessagesGet($userParamArr);
		if($result[code]){//写出错日志  
			  echo ('taobao[TOP_RefundMessagesGet]方法请求失败!'.':['.$result[code].']'.$result[msg]); 
		 }else { 
		 	  foreach ( $result['list'] as $row  ){ 
		 	   	OS_InsertIntoTB('tb_refundmessage','id',$row );  ////留言/凭证数据结构 
		 	  }
		 }   		
	}
	/**
	 * 退货转退订
	 * 影响订单主表: return_status(退货状态)0未退货;1部分退货申请中,2全部退货申请中,3已部分退货,4已经全部退货
	 * 影响订单主表: refund_status(退款状态)0未退款;1部分退款申请中,2全部退款申请中,3已部分退款,4已经全部退款  
	 * 以下影响明细表：
	 * is_good_received	是否收到货
	 * return_desc	退货说明
	 * goods_status	商品状态
	 * payment	支付商家费用
	 * has_goods_return	是否退货 
	 * */
	function refund2return($refund_id){  //has_good_return买家是否需要退货。可选值:true(是),false(否) 
		global $_CFG, $db,$os ;   
		if( $refund_id && !Check_is_exist('tb_refund','refund_id',$refund_id)  ) GetArrRefundGet($refund_id);   //本地不存则先下载
		$has_good_return = Check_is_exist('tb_refund','refund_id',$refund_id,'','has_good_return');
		//if(() && $has_good_return == 'true') { //是否有退货
		if(($tid = Check_is_exist('tb_refund','refund_id',$refund_id,'','tid')) && !Check_is_exist('tb_trade','tid',$tid) ) {
			echo ('交易正在下载并转订单....<br/>');
			TradeToOrder($tid);   //先交易转订单然后。退单关联此订单
			echo ('交易转订单成功....<br/>正在退货转退单.....<br/>');
		} 
		$order_sn = Check_is_exist('tb_trade','tid',$tid,'','outer_order_sn');   //OS_订单号
		$oid = Check_is_exist('tb_refund','refund_id',$refund_id,'','oid'); 	 //TOP_子订单号 
		$result['orders']['order'] = $db->getAll("select * from open_tb_order where tid='".$oid."'"); 
	    $result =GetArrTradeGet($tid) ;  //高性能发交易状态并比较 本地交易状态发生变化则再次更新  
		if( (Check_IsDownTradeBySeller_memo( $result['trade'], 1)) && (CheckOrder_goods( $result , $type))  ) {  //验证通过交易中商品 //(Check_IsDownTradeBySeller_memo($result['trade'])) && 
			//$isnew = $db->getOne("select o_r.id from open_tb_refund as tb_r   left join open_order_return as o_r on o_r.return_sn = tb_r.outer_return_sn    where refund_id='".$refund_id."'") ;  //是否为新增
			$order_return_id = InsertIntoOrder_return($order_sn ,$tid,$refund_id );  //插入退单主表order_return_return   
			if( $has_good_return == 'true' ) InsertIntoOrder_Return_goods($order_sn,$order_return_id ,$tid , $oid,$refund_id ); //插入表IntoOrder_Return_goods  如果退货  
			echo ('TOP退货:['.$refund_id.'],交易:['.$tid.'],转退单:<a href="order.php?act=returned_order_info&order_return_id='.$order_return_id.'" target="_blank">['.Check_is_exist('order_return','id',$order_return_id,'','return_sn').']</a>成功! 关联订单:<a href="order.php?act=info&order_id='.Check_is_exist('order_info','order_sn',$order_sn,'','order_id').'" target="_blank">['.$order_sn.']</a>     <a href="#" onclick="history.go(-1)">返回</a><br/>');  
			Change_order_status( $order_sn,$order_return_id,$refund_id );//退货后更新订单状态信息 by winner add 改订单主表中的 退款，退货 状态	  
			//if( !$isnew ){  //回写备注转退单成功 
			$new_seller_memo = $result['trade']['seller_memo'] ."\n \r---->此退货已在".date('Y-m-d H:i:s')."已关联B2C[待验货] 退单号:".Check_is_exist('order_return','id',$order_return_id,'','return_sn')  ; 
			UpdateTradeMemo($tid,$new_seller_memo );
			//	} 
		 } 
		//}else {
		//	echo ('没有退商品...不能转成退货单!');
		//} 
	}
	/**
	 * 退货/款成功后 改变 主订单状态
	 * return_status   refund_status
	 * 0未退货           0未退款
	 * 1部分退货申请中，  1部分退款申请中，	
	 * 2全部退货申请中，  2全部退款申请中，	
	 * 3已部分退货，     3已部分退款	
	 * 4已全部退货 ，    4已全部退款，
	 * */
	function Change_order_status( $order_sn, $order_return_id,$refund_id ){//退货后更新订单状态信息//如果原订单 未退货，       未退款， 改成退货/退款申请中。。。
		global $_CFG, $db,$os ;   
		$order_total_fee = Check_is_exist('order_info','order_sn',$order_sn,'','money_paid') ; //订单总数量 
		$order_buyer_num = $db->getOne("select sum(goods_number)  from open_order_goods as og left join open_order_info as oi on oi.order_id=og.order_id
								where oi.order_sn='".$order_sn."'") ; //订单总金额
		$return_order_num = $db->getOne("select sum(return_total_fee)  from open_order_return 
								where relating_order_sn='".$order_sn."'"); //所有关联退单 总金额
		$return_order_total_fee = $db->getOne("select sum(goods_return_number) from open_order_return_goods as org left join open_order_info as oi on oi.order_id=org.order_id
								where oi.order_sn='".$order_sn."'");   //所有关联退单总 数量 
        if(Check_is_exist('tb_refund','refund_id',$refund_id,'','has_good_return')=='true'){
			if($order_buyer_num == $return_order_total_fee){ //购买数等于退货数
			   Update_table_key('order_info','return_status',2," order_sn ='".$order_sn."'"); // 改成 完全退货申请中。。
			}else {
			   Update_table_key('order_info','return_status',1," order_sn ='".$order_sn."'"); // 改成 部分退货 申请中。。。  
			} 
		} 
		if( $order_total_fee == $return_order_total_fee) {
			Update_table_key('order_info','refund_status',2," order_sn ='".$order_sn."'"); //  完全退款申请中。。。
		}else {
			Update_table_key('order_info','refund_status',1," order_sn ='".$order_sn."'"); //  部分退款申请中。。。
		} 
	 }	
	/**
	 * 插入退单主表order_return_return  插入新的退货单订单，状态为确认
	 * 影响订单主表: return_status(退货状态)0未退货;1部分退货申请中,2全部退货申请中,3已部分退货,4已经全部退货
	 * 影响订单主表: refund_status(退款状态)0未退款;1部分退款申请中,2全部退款申请中,3已部分退款,4已经全部退款
	 * is_good_received	是否收到货
	 * return_desc	退货说明
	 * goods_status	商品状态
	 * payment	支付商家费用
	 * has_goods_return	是否退货     
	 * */
	function InsertIntoOrder_return($order_sn ,$tid,$refund_id){
		global $_CFG, $db,$os ;   
		$order_return = array();
		$relating_order_sn	= $order_sn;
	    $sql =  'select count(*) from '.$os->table('order_return').' where relating_order_sn = "'.$relating_order_sn.'" and return_order_status <> '.RS_INVALID;
	    $count = $db->getOne($sql);  
		if($count == 1) return Check_is_exist('order_return','relating_order_sn',$relating_order_sn,'','id')  ;  
		$row_order_info=$db->getRow("select * from open_order_info where order_sn='".$relating_order_sn."'");
		$return_goods_amount = intval($_POST['return_goods_amount']);
		$admin_user ='auto_os_admin' ;//$_SESSION['admin_name']; 
		$order_return['relating_order_sn']      = $relating_order_sn;
		$order_return['return_reason']			= '6'; // intval($_POST['return_reason']); 与商品描述不符
		$order_return['return_pay'] 			= '1'; //intval($_POST['return_pay']); 退到个人账户
		$order_return['return_consignee'] 		= Check_is_exist('order_info','order_sn',$order_sn,'','consignee')   ;// $_POST['return_consignee'];
		$order_return['return_email'] 			= Check_is_exist('order_info','order_sn',$order_sn,'','email')   ;// $_POST['return_email'];
		$order_return['return_address'] 		= Check_is_exist('order_info','order_sn',$order_sn,'','address')   ;//$_POST['return_address'];
		$order_return['return_zipcode'] 		= Check_is_exist('order_info','order_sn',$order_sn,'','zipcode')   ;// $_POST['return_zipcode'];
		$order_return['return_tel'] 			= Check_is_exist('order_info','order_sn',$order_sn,'','tel')   ;// $_POST['return_tel'];
		$order_return['return_mobile'] 			= Check_is_exist('order_info','order_sn',$order_sn,'','mobile')   ;// $_POST['return_mobile'];
		$order_return['action_user']  			= $admin_user;
		$order_return['return_goods_amount'] 	= 1; //默认1件 后根据明细更新
		$order_return['return_total_fee'] 	= 1;	 //默认1元 后根据明细更新
		$order_return['return_sn'] 				= get_order_return_sn();
		$order_return['return_order_status']    = RS_CONFIRMED;
		$order_return['add_time']    			= gmtime();
		
		$order_return['is_good_received'] =Check_is_exist('tb_refund','refund_id',$refund_id,'','is_good_received')    ;  //is_good_received	是否收到货
		$order_return['return_desc'] = Check_is_exist('tb_refund','refund_id',$refund_id,'','refund_desc') ;//return_desc	退货说明
		$order_return['goods_status'] =Check_is_exist('tb_refund','refund_id',$refund_id,'','goods_status')   ;//goods_status	商品状态
		$order_return['payment'] = Check_is_exist('tb_refund','refund_id',$refund_id,'','payment') ;//payment	支付商家费用
		$order_return['has_goods_return'] = Check_is_exist('tb_refund','refund_id',$refund_id,'','has_goods_return') ;//has_goods_return	是否退货
        
		OS_InsertIntoTB('order_return','return_sn',$order_return);	 //更新或插入订单主表  可以在此加条件  
		$order_return_id = Check_is_exist('order_return',return_sn,$order_return['return_sn'],'',"id"); // $db->insert_id(); 
		Update_table_key('tb_refund','outer_return_sn',$order_return['return_sn'],"refund_id='".$refund_id."'");  //更新关联表的tb_trade表中outer_order_sn 
		$action_note= Check_is_exist('tb_refundmessage',refund_id,$refund_id,'',"content");
		$log_already = order_return_action_judge($order_return_id, RS_CONFIRMED, $action_note,$admin_user);
		if(!$log_already) order_return_action($order_return_id, RS_CONFIRMED, $action_note,$admin_user); 
		return $order_return_id ;  	 
	}
	/**
	 * 插入表IntoOrder_Return_goods
	 * */
	function InsertIntoOrder_Return_goods($order_sn,$order_return_id ,$tid , $oid,$refund_id ){ 
		global $_CFG, $db,$os ;  
		 $sql="select refund_id,tr.num as re_num,g.goods_name,tbo.tid,tbo.outer_iid,tbo.num as buy_num,tbs.properties,g.goods_id,g.shop_price,g.market_price,cid 
               from open_tb_refund as tr
		 	   left join open_tb_order as tbo on tbo.tid=tr.oid    
               left join open_tb_sku as tbs on tbs.sku_id=tbo.sku_id      
               left join open_goods as g on g.goods_sn=tbo.outer_iid 
               left join open_tb_item as tbi on tbi.outer_id=tbo.outer_iid  	 
		 	   where refund_id='".$refund_id."' ";  
		if(!$row = $db->getRow($sql)){
		  	echo ($refund_id.'退单没有存在!');
		} else { 
			$cid = $row['cid'];
			$goods_sn = $row['outer_iid']; 
			$guige_arr = getGuigeByProperties( $row['properties'] ,$cid,$goods_sn) ; 
			$color_id = $guige_arr['color_id'] ;
			$size_id = $guige_arr['size_id']  ;  
			$order_return_goods =array(
		 					'return_order_id' => $order_return_id ,  //传过来的。
			    			'order_id' => Check_is_exist('order_info','order_sn',$order_sn,'',"order_id") , //关联订单ID
			    			'goods_id' => $row['goods_id']  ,
			    			'goods_name' => $row['goods_name']  ,
			    			'goods_sn' => $goods_sn  ,
			    			'goods_return_number' => $row['re_num']  ,
			    			'goods_buy_number' => $row['buy_num']  , 
			    			'market_price' => $row['market_price'] ,
			    			'goods_price' => $row['shop_price'] ,
			    			'color_id' => $color_id,
			    			'size_id' => $size_id,
			    			'is_real' => 1, 
			    			'extension_code' => '',
			    			'parent_id' => 0,
			    			'is_gift' => 0, 
		 			); 
		    OS_InsertIntoTB('order_return_goods','return_order_id',$order_return_goods,"goods_id ='".$row['goods_id']."' and color_id ='".$color_id."' and size_id='".$size_id."'"); 
		    $outer_return_goods_id =Check_is_exist('order_return_goods','return_order_id',$order_return_id,"goods_id ='".$row['goods_id']."' and color_id ='".$color_id."' and size_id='".$size_id."'",'id'); 
		    Update_table_key('tb_refund','outer_return_goods_id',$outer_return_goods_id,"refund_id='".$refund_id."'");  //更新关联表的 写明细
		    Update_table_key('tb_refund','outer_return_sn',Check_is_exist('order_return','id',$order_return_id,'','return_sn'),"refund_id='".$refund_id."'");  //更新关联表的主表SN
		}    
		$sql="update open_order_return set 
			 return_goods_amount = (select sum(goods_return_number) from open_order_return_goods where return_order_id='".$order_return_id."') ,
			 return_total_fee =( select sum(goods_price) from open_order_return_goods where return_order_id='".$order_return_id."')
			 where id = '".$order_return_id."' "; 
		$db->query($sql);// 更新数据库表中的退货单总 数量与 金额
 	}
	/**
	 * taobao.trade.get 
	 * */
	function GetArrTradeGet($tid){
		$userParamArr = array(
						'fields' => 'seller_nick, buyer_nick, title, type, created, sid, tid, seller_rate, buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path, iid, num, price, cod_fee, shipping_type,orders ',
						'tid' =>  $tid
					);      
	    return TOP_TradeGet($userParamArr);  
	}
	/**
	 *  单笔交易转订单 
	 *  不强转商品.没有商品提示$type=''
	 * */
	function TradeToOrder($tid,$type=''){ 
		//echo $tid ."<BR/>";
		global $_CFG, $db,$os ;  
		if( $tid && !Check_is_exist('tb_trade','tid',$tid)  )   
		{
			DownTradeByTid($tid);   //本地不存则先下载
		}
		$result =GetArrTradeGet($tid) ;  //高性能发交易状态并比较 本地交易状态发生变化则再次更新  
		if( is_array($result['trade']) && $result['trade']['status'] != Check_is_exist('tb_trade','tid',$tid,'','status') )  
		{
			DownTradeByTid($tid); //状态发生变化则再次更新  
		}
        if(is_array($result['trade']) && $result['trade']['buyer_nick'] )
		{
 			$os_user_id = BuyerToUser($result['trade']['buyer_nick']) ;//如果买家存在则转会员//更新送货时间，标致物 
 		}     
  	    if( $result['trade'] &&  (Check_IsDownTradeBySeller_memo($result['trade'])) && (CheckOrder_goods( $result['trade'] , $type)) )
		{  //验证通过交易中商品 
			$order_id = InsertIntoOrder_info( $result['trade'] , $os_user_id );  //插入表order_info   
			$is_new =Check_is_exist('order_goods','order_id',$order_id,'','rec_id'); 
			InsertIntoOrder_goods( $result['trade'], $order_id ); //插入表order_goods  
			if( (!$is_new) ){ 
			    //change_goods_inventory($order_id,true); //不存在表示新增的/* 如果使用库存，且下订单时减库存，则修改库存 */
			    manage_good_inventory(  $order_id , 'order'  );
			} 
			auto_update_shipping_delivery( $order_id , '' );  // 修改计划发货时间调用这个接口 
		    if( Check_is_exist('order_info','order_id',"$order_id","",'process_status') ){
				$new_seller_memo = $result['trade']['seller_memo'] ."  \n \r---->此交易在".date('Y-m-d H:i:s')."已关联B2C[待确认]  订单号:".Check_is_exist('order_info','order_id',$order_id,'','order_sn')  ; 
			}else {
				$new_seller_memo = $result['trade']['seller_memo'] ."  \n \r---->此交易在".date('Y-m-d H:i:s')."已关联B2C[待发货]  订单号:".Check_is_exist('order_info','order_id',$order_id,'','order_sn')  ; 
			} 
			UpdateTradeMemo($tid,$new_seller_memo );
			Orders_list_merge_split( $order_id ) ; //尝试合并订单尝试折分订单 
			echo ('TOP交易:['.$result['trade']['tid'].'],转订单:<a href="order.php?act=info&order_id='.$order_id.'" target="_blank">['.Check_is_exist('order_info','order_id',$order_id,'','order_sn').']</a>成功!  <a href="#" onclick="history.go(-1)">返回</a><br/>');  
	    } 
	}
	/**
	 *  尝试合并订单尝试折分订单
	 * **/
	function Orders_list_merge_split($order_id){
		global $_CFG, $db,$os ;  
		  $use_auto_merge = get_code_value(get_tb_settings(null),'use_auto_merge') ;//use_auto_merge 启用启用自动合单 
		  $use_auto_merge_time = get_code_value(get_tb_settings(null),'use_auto_merge_time') ;//合并时间
		  $use_auto_cut = get_code_value(get_tb_settings(null),'use_auto_cut') ;//use_auto_merge 启用 启用自动折单
		  $use_auto_cut_actuals_sell = get_code_value(get_tb_settings(null),'use_auto_cut_actuals_sell') ;//现货预售并存 
		  if( $use_auto_merge ){  //自动合单  
		  	 echo '启用自动合单<br/>';
		  	 $user_id = Check_is_exist('order_info','order_id',$order_id,'',"user_id");
			 $add_time = Check_is_exist('order_info','order_id',$order_id,'',"add_time"); 
		     $temp_time = $add_time - 3600 * $use_auto_merge_time ; //小时
		  	 $sql="select order_sn from open_order_info where user_id='".$user_id."' and shipping_status<>1 and add_time>".$temp_time ." order by order_id desc" ;  //在规定时间内未发货的订单
		     $order_sns = $db->getCol($sql);  
   		     if( count($order_sns)>1 )$result = merge_orders($order_sns);   
		  }
		  if ($use_auto_cut){ //启用自动折单
		  	 echo '启用自动折单<br/>';
		  	 $sql="select  DISTINCT(g.is_promote)  from open_order_goods as og
					left join open_goods as g on g.goods_id=og.goods_id where order_id= '".$order_id."' "; 
		  	  $rows = $db->getAll($sql);	 //大于0	
			 if( is_array($rows) && count( $rows )>1 ){ //同时具有 is_promote 0/1  订单中  现货预售并存  可以折分功能 
			     $sql="select rec_id  from open_order_goods as og left join open_goods as g on g.goods_id=og.goods_id where g.is_promote=1 and order_id=".$order_id;//把 预售商品rec_id选出来。
				 $selected_goods_rec_id = $db->getCol($sql);	 //大于0		
			     if( $selected_goods_rec_id ) split_order($order_id,$selected_goods_rec_id); //调用折分功能涵数
			 } 
		  } 
	} 
   /**
	 * 回写TOP交易备注
	 * */
	 function UpdateTradeMemo($tid,$new_seller_memo ){
	   		$userParamArr = array(
								'memo' =>$new_seller_memo,
								'tid' =>  $tid
							); 
			$result = TOP_TradeMemoUpdate( $userParamArr ) ; //回写TOP备注 
			if($result[code]){//写出错日志  
				echo ('taobao.'.$method.'方法请求失败!'.':['.$result[code].']'.$result[msg]); 
			 }  
	 }
	/**
	 *  根据TOP交易单上的卖家备注进行判断是否下载此交易  $is_refund//是验证退单
	 * */
	function Check_IsDownTradeBySeller_memo( $trade ,$is_refund=''){
		$seller_memo = $trade['seller_memo']; 
	    $use_buss_desc = get_code_value(get_tb_settings(null),'use_buss_desc') ;  //得到是否启用商家备注 
	    if(!$use_buss_desc) return true; //商家备注 未启用。则返回全部下载
	    $use_buss_desc_no = get_code_value(get_tb_settings(null),'use_buss_desc_no') ; //没有备注。操作1转订单 2不转订单 
	    if( $use_buss_desc && ($use_buss_desc_no==2) ) return false ; //如果启用商家备注并 设置不备注不转订单
	    if( $use_buss_desc && ($use_buss_desc_no==1) && !$seller_memo ) return true;   //如果启用商家备注并 备注为空 设置不备注 直接转订单 
		if($is_refund){  //退款下载验证
			if( strstr($seller_memo, get_code_value(get_tb_settings(null),'Refund_tag')  ) ){
				return true; 
			}else {
				echo ('TOP退款:'.$trade['tid'].',卖家备注:'.$seller_memo.',<br/>[转退货单]验证未通过!备注中未包含:'.get_code_value(get_tb_settings(null),'Refund_tag').'  <a href="#" onclick="history.go(-1)">返回</a><br/>');  
	  			return false; 
			} 
		}else {  	   //交易下载验证
			if(!get_code_value(get_tb_settings(null),'download_tag')) { 
				 return true; //下载标致位不存在 系统未设定。全部下载
			 }elseif (  strstr($seller_memo, get_code_value(get_tb_settings(null),'download_tag')  )   ){//根据标致位判断是否下载此交易 ,(系统设置中下载标至位存并等于top上的备注) 或  (系统中挂起标至位存在并等到top中的备注)   如果备注中存在 $result['trade']['seller_memo']	
				 return true; //下载标致位存在 仅下载备注中包含 系统中设定字符
			 }elseif ( (get_code_value(get_tb_settings(null),'lock_tag')) &&   (strstr($seller_memo,get_code_value(get_tb_settings(null),'lock_tag')))  ){//根据标致位判断是否下载此交易 ,(系统设置中下载标至位存并等于top上的备注) 或  (系统中挂起标至位存在并等到top中的备注)   如果备注中存在 $result['trade']['seller_memo']
		  			return true;	//挂起存在并 备注中包含有挂起字符串
	  		}else {  
	  			echo ('TOP交易:'.$trade['tid'].',卖家备注:'.$seller_memo.',<br/>[转订单]验证未通过!备注中未包含:'.get_code_value(get_tb_settings(null),'lock_tag').'或'. get_code_value(get_tb_settings(null),'download_tag').'   <a href="#" onclick="history.go(-1)">返回</a><br/>');  
	  			return false;
	  		}
		} 
	}
	/**
	 * taobao.trade.fullinfo.get(获取单笔交易的详细信息) 
	 * 
	 * */
	function TradeFullinfoGet( $tid ){
		    global $_CFG, $db,$os,$topParamArr; 
			$aryy1=$topParamArr;
			$aryy1['method']='taobao.trade.fullinfo.get';
			//API用户参数
			$userParamArr = array(
					'fields' => 'seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status, payment,discount_fee,adjust_fee, post_fee,total_fee,pay_time,end_time,modified,consign_time, buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee, buyer_memo,seller_memo,alipay_no,buyer_message,pic_path,iid,num,price, buyer_alipay_no,receiver_name,receiver_state,receiver_city,receiver_district, receiver_address,receiver_zip,receiver_mobile,receiver_phone,buyer_email, seller_alipay_no,seller_mobile,seller_phone,seller_name,seller_email, available_confirm_fee,has_postFee,timeout_action_time,snapshot_url,cod_fee,shipping_type,trade_memo,orders',
					'tid' => $tid
				);  
			$result = lib_getArray_params($aryy1 + $userParamArr);  
			InsertIntoOrder($result['trade']); //传订单信息	
	} 
	/**
	 * 根据tid下载到数据到tb_trade与tb_order表
	 * */
	function  GetInsertIntoTrade($tid){
		$userParamArr = array(
						'fields' => 'seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status, payment,discount_fee,adjust_fee, post_fee,total_fee,pay_time,end_time,modified,consign_time, buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee, buyer_memo,seller_memo,alipay_no,buyer_message,pic_path,iid,num,price, buyer_alipay_no,receiver_name,receiver_state,receiver_city,receiver_district, receiver_address,receiver_zip,receiver_mobile,receiver_phone,buyer_email, seller_alipay_no,seller_mobile,seller_phone,seller_name,seller_email, available_confirm_fee,has_postFee,timeout_action_time,snapshot_url,cod_fee,shipping_type,trade_memo,orders',
						'tid' =>  $tid
					);    
		$result = TOP_TradeFullinfoGet($userParamArr); 
		InsertIntoOrder($result['trade']); //传订单信息	
	}
	 /**
	  *  交易转订单  插入B2C 表order_info,order_goods
	  */
	  function  InsertIntoOrder($result){    
	  	 //得到用户ID 如果不存则插入新用户 
	      $user_id = Get_user_id ($result); 
		  if( CheckOrder_goods( $result ) ){
				//插入表表order_info  
				$order_id = InsertIntoOrder_info($result,$user_id);
				//插入表order_goods
				InsertIntoOrder_goods($result,$order_id ); 
		  } 
	  }   	
	/**
	 * 根据tid下载到数据到tb_trade与tb_order表
	 * */
	function  DownTradeByTid($tid)
	{
        $userParamArr = array(
				'fields' => 'seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status, payment,discount_fee,adjust_fee, post_fee,total_fee,pay_time,end_time,modified,consign_time, buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee, buyer_memo,seller_memo,alipay_no,buyer_message,pic_path,iid,num,price, buyer_alipay_no,receiver_name,receiver_state,receiver_city,receiver_district, receiver_address,receiver_zip,receiver_mobile,receiver_phone,buyer_email, seller_alipay_no,seller_mobile,seller_phone,seller_name,seller_email, available_confirm_fee,has_postFee,timeout_action_time,snapshot_url,cod_fee,shipping_type,trade_memo,orders',
				'tid' =>$tid
						);   
		$result = TOP_TradeFullinfoGet($userParamArr);   
		if (is_array($result['trade']) &&  $result['trade']['buyer_nick']) 
		{
			GetInsertUserById($result['trade']['buyer_nick']  );   //向此单中下载购货人信息
			 /*******更新tb_user相关表*******/
			$arr = array(
						'nick' => $result['trade']['buyer_nick'],
						'real_name' =>$result['trade']['receiver_name'],
						'phone' =>$result['trade']['receiver_phone'],
						'mobile' =>$result['trade']['receiver_mobile'],
						'email' =>$result['trade']['buyer_email'],
						'alipay_no' =>$result['trade']['buyer_alipay_no'],
					);
			 OS_InsertIntoTB('tb_user','nick',$arr);		
			 $arr = array(
			 			'user_id' =>Check_is_exist('tb_user','nick',$result['trade']['buyer_nick'],'','user_id'),
						'nick' =>$result['trade']['buyer_nick'],
						'zip' =>$result['trade']['receiver_zip'],
						'address' =>$result['trade']['receiver_address'],
						'city' =>$result['trade']['receiver_city'],
						'state' =>$result['trade']['receiver_state'],
						'country' =>$result['trade']['receiver_country'],
						'district' =>$result['trade']['receiver_district'],
					);
			 OS_InsertIntoTB('tb_location','nick',$arr);	 
			 if(is_array($result['trade']) &&  Check_is_exist('tb_user','nick',$result['trade']['buyer_nick'],"location='Array'") )
			 Update_table_key('tb_user','location',Check_is_exist("tb_location",'nick',$result['trade']['buyer_nick']),"nick='".$result['trade']['buyer_nick']."'") ; //更新主表tb_user表location_id			
		}
		if(is_array($result['trade']) && $result['trade']['sid'] )
		{
			GetMyShippingByTid( $result['trade']['sid'] ) ; //向此单中下载物流 
		}
		if( !$result['trade']['num'] && is_array($result['trade']['orders']['order']) )
		{  
			foreach ($result['trade']['orders']['order']  as $goods)
			{
				$result['trade']['num'] =$result['trade']['num'] + $goods['num']  ;  ////如果这个不存在。则说明明细表多条记录数量累加
			}
		}
		OS_InsertIntoTB('tb_trade','tid',$result['trade']);
		if(is_array($result['trade']) && is_array($result['trade']['orders']['order']))
		{
			$orders = $result['trade']['orders']['order']; 
		}
	    if(is_array( $orders ) && is_array( $orders[0]) )
		{
	    	 foreach ($orders as $order)
			 {
	    	 	$iid= $order['iid'];
	    	 	if($sku_id= $order['sku_id']){
	    	 		OS_InsertIntoTB('tb_order','tid',$order,"iid='".$iid ."' and sku_id='".$sku_id."'" );
	    	 	}else{
	    	 		OS_InsertIntoTB('tb_order','tid',$order,"iid='".$iid."'" );
	    	 	}
	    	 }
	    }
		else 
		{//单件商品   
	    	$iid= $orders['iid'];
	    	if($sku_id= $orders['sku_id'])
			{
    	 		OS_InsertIntoTB('tb_order','tid',$orders,"iid='".$iid ."' and sku_id='".$sku_id."'" );
    		}
			else
			{
    	 		OS_InsertIntoTB('tb_order','tid',$orders,"iid='".$iid."'" );
    		}   
	    }
		echo ('TOP交易:['.$tid.']下载成功! <a href="#" onclick="history.go(-1)">返回</a><br/>');
	}
	/**
	 * 下载订单前检查 基本信息完善性 返回值为正
	 * */
	function CheckOrder_goods( $result, $type='' ){
		 global $db,$os; 
		 if(is_array($result['orders']) && is_array($result['orders']['order']) && $result['orders']['order'][0] ) {   
		 		$real_list=$result['orders']['order'];
		 }elseif (is_array( $result['orders']) ) {
		 	    $real_list[0] = $result['orders']['order']; 
		 }
		foreach( $real_list AS $list ) { 
				$iid = $list['iid']; 	//商品iid
				$sku_id = $list['sku_id'];  
				if(!Check_is_exist('tb_item','iid',$iid)) GetTBOneItem( $iid ) ;  //此商品本地数据库中没有,未下载则先下载商品 
				if($sku_id && !Check_is_exist('tb_sku','sku_id',$sku_id) ) GetInsertIntoSKU( $sku_id ); //如果sku不在本地数据表则再次请求
			 	$sql="select num_iid,title,cid,property_alias,goods_id,goods_sn from ". $os->table('tb_item') ." left join ". $os->table('goods') ."  on outer_id=goods_sn
					  where iid='$iid' ";   //得到goods_id   
			    $goods_row = $db->getRow($sql); 
			    if((!$goods_sn = $goods_row['goods_sn']) && (!$type) ) {
			    	echo ('宝贝:'.$iid.'['.$goods_row['num_iid'].']'.$goods_row['title'].'  未关联起来,请手工关联商品!<br/>') ;  
			    	return false;
			    }elseif ( (!$goods_sn =$goods_row['goods_sn']) && $type ) {
			    	TOP_item2OS_goods($iid);
			    } 
				$goods_id =$goods_row['goods_id']  ;  
				$cid = $goods_row['cid']  ;  
				$property_alias =$goods_row['property_alias'];  //颜色别名
			    if( $sku_id ){ //说明颜色尺码存在
			    	$properties= $db->getOne("select properties from open_tb_sku where sku_id='".$sku_id."'")  ; //得到SKU中的属性 	
			    	$guiges = explode(';', $properties );  
					$guige1= explode(':',$guiges[0] )  ;  //颜色:白色
					$vid = $guige1[1] ;  
					$sql= "select c.color_id from open_tb_guige1 as tb_gg1 left join open_color as c on tb_gg1.color_code=c.color_code where tb_gg1.cid='".$cid."' and tb_gg1.vid='".$vid."'";
					if( !$color_id = $db->getOne($sql) ) {   
						//AutoExeGuige($goods_sn,$property_alias,$cid);  //自动关联属性有问题，故注销掉flying.liu 2010.04.07
							$sql= "select c.color_id from open_tb_guige1 as tb_gg1 left join open_color as c on tb_gg1.color_code=c.color_code where tb_gg1.cid='".$cid."' and tb_gg1.vid='".$vid."'";
						if( !$color_id = $db->getOne($sql)  ) {
							echo ('Check商品['.$goods_sn.']颜色仍未关联到TOP:['.$cid.']类目,属性值:['.$vid.']'.Check_is_exist('tb_guige1','vid',$vid,"cid='".$cid."'","name") .' <br/>请手工关联!<br/><a href="#" onclick="history.go(-1)">返回</a><br/>' ) ; 
							return false;
						}
				    }  
				    $guige2= explode(':',$guiges[1])  ;  //尺码
				    $vid = $guige2[1] ;
				    if($vid && $vid!=''){
							$sql= "select s.size_id from open_tb_guige2 as tb_gg2 left join open_size as s on tb_gg2.size_code=s.size_code where tb_gg2.cid='".$cid."' and tb_gg2.vid='".$vid."'";
				  		   
				    		if(  !$size_id = $db->getOne($sql) ) {  
								//AutoExeGuige($goods_sn,$property_alias,$cid);//自动关联属性有问题，故注销掉flying.liu 2010.04.07
								$sql= "select s.size_id from open_tb_guige2 as tb_gg2 left join open_size as s on tb_gg2.size_code=s.size_code where tb_gg2.cid='".$cid."' and tb_gg2.vid='".$vid."'";
								if(  !$size_id = $db->getOne($sql)  ) {
							    	echo ('Check商品['.$goods_sn.']尺码仍未关联到TOP:['.$cid.']类目,属性值:['.$vid.']'.Check_is_exist('tb_guige1','vid',$vid,"cid='".$cid."'","name") .' <br/>请手工关联!<br/><a href="#" onclick="history.go(-1)">返回</a><br/>' ) ; 
							    	return false;
 							    	}
				  			}
				    }  
			 }   
		 }    
		return true;
	} 
	/**
	 * 生成唯一 订单号 
	 * */
     function GetOnly_Order_sn(){ 
		 do{
		    $order_sn = get_order_sn();
		    if(!Check_is_exist('order_info','order_sn',$order_sn,'','order_id' ) ) break; 
		   }	
		 while (true); // 防止订单号重复   
		 return $order_sn;	 
     }
  /**
	* 插入表表order_info
	*/
	function  InsertIntoOrder_info($result,$user_id){  
		// [sid] => 物流 Shipping 的id  
		//shipping_type 创建交易时的物流方式 
	   global  $exc, $db,$os ;  
	   /**
	    *TRADE_NO_CREATE_PAY(没有创建支付宝交易)
	    * WAIT_BUYER_PAY(等待买家付款)
	    * WAIT_SELLER_SEND_GOODS(等待卖家发货,即:买家已付款)
	    * WAIT_BUYER_CONFIRM_GOODS(等待买家确认收货,即:卖家已发货)
	    * TRADE_BUYER_SIGNED(买家已签收,货到付款专用)
	    * TRADE_FINISHED(交易成功)
	    * TRADE_CLOSED(交易关闭)
	    * TRADE_CLOSED_BY_TAOBAO(交易被淘宝关闭)
	    * ALL_WAIT_PAY(包含：WAIT_BUYER_PAY、TRADE_NO_CREATE_PAY)  
	    * ALL_CLOSED(包含：TRADE_CLOSED、TRADE_CLOSED_BY_TAOBAO) 
	    * */ 
	   if( !is_array($result) ) return ;
		$order_status=0;    //未确认
		$pay_status=0;      //未付款
		$shipping_status=0; //未发货 
        $order_amount = 0 ; 
        $discount = $result['received_payment'] - ($result['goods_amount'] + $result['shipping_fee'] - $result['discount_fee'] - $result['adjust_fee'])   ;  //订单还应交费用  
	    if( $result['status'] =='WAIT_SELLER_SEND_GOODS' ) 
		{	 
	    	$pay_status= 2;  //已付款//$arr['money_paid'] = $result['payment'] ; //已付金额 
	    	$money_paid = $result['payment']  ;
	    }
		else
		if (  $result['status'] =='WAIT_BUYER_CONFIRM_GOODS' || $result['status'] =='TRADE_BUYER_SIGNED' || $result['status'] == 'TRADE_FINISHED' ) 
		{  
	        $pay_status= 2;       //2已付款 
	        $money_paid = $result['payment']  ; 
	        if( $result['status'] =='TRADE_FINISHED' ) 	$pay_status= 3;     //3已结算
	        $order_status=1;      //已确认
	        $shipping_status = 1; //已发货 
	   }elseif (  $result['status'] =='TRADE_CLOSED' || $result['status'] =='TRADE_CLOSED_BY_TAOBAO' ) 
		{     //作费 
			$order_status=6;       //作费 
		    $order_amount =  $result['payment']; 
	   }else  
		{
		   	  $pay_status= 0; 	      //未付款
		   	  $order_amount =  $result['payment']; 
	   }
	   $shipping_type = $result['shipping_type'];  //post express  ems  三种运送方式    
	   $sql="select tb_t.*,o.order_id,o.order_sn from open_tb_trade tb_t 
			 left join open_order_info o on o.order_sn=tb_t.outer_order_sn
			 where tb_t.tid='".$result['tid']."'"; 
	   $tb_trade = $db->getRow($sql);  //taobao交易表信息
	   if(!$order_sn = $tb_trade['order_sn'] ) 
		{
			$order_sn= GetOnly_Order_sn(); //如果订单已经存在 已经有关联的订单号   原订单号/得到新订单号
		}
	   $shipping_out_sid = Check_is_exist('tb_my_shipping','tid',$result[tid],'','out_sid') ; 
	   if( $shipping_company_name = Check_is_exist('tb_my_shipping','tid',$result[tid],'','company_name') )
		{
		   	  if( !$shipping_company_code = Check_is_exist('tb_shipping','company_name',$shipping_company_name,'','company_code') ) 
				InsertIntoTB_shipping();//如果不存在，则下载并自动关联
			  if( ( $shipping_company_code = Check_is_exist('tb_shipping','company_name',$shipping_company_name,'','company_code')) && (!$shipping_field1= Check_is_exist('tb_shipping','company_name',$shipping_company_name,'','field1')) )
				{
			  		  $shipping =array(
									shipping_code =>$shipping_company_code,
									shipping_name =>$shipping_company_name,
									shipping_desc =>$shipping_company_name,
									insure  =>'0',
									support_cod  =>'0',
									enabled  =>'1',
					  	 	   ); 
				  	 OS_InsertIntoTB('shipping','shipping_code',$shipping );  //插入shipping表中;
				  	 Update_table_key('tb_shipping','field1',$shipping_company_code,"company_code='".$shipping_company_code."'");
				  }   
			  $sql ="select shipping_id as shipping_id  from ".$os->table('tb_my_shipping')." as tb_my_sp left join 
					".$os->table('tb_shipping') ." as tb_sp on  tb_sp.company_name=tb_my_sp.company_name left join
					".$os->table('shipping')." as sp on sp.shipping_code= tb_sp.field1  where tid='$result[tid]' ";  
			  $shipping_id = $db->getOne($sql);   //已发货的shipping_id;
	    }
		/* 插入新订单，状态为无效 */
		$order = array(
					'user_id'           => $user_id ,
					'order_sn'          => $order_sn ,
					'discount'          => abs($discount) ,
					'add_time'          => gmstr2time( $result['created']  ),		 //
				    'shipping_time'     => gmstr2time( $result['consign_time']), 	 //consign_time
					'order_status'      => $order_status,
					'money_paid'        => $money_paid,
					'order_amount'      => $order_amount,
					'shipping_status'   => $shipping_status,
					'pay_status'        => $pay_status ,   //支付
					'from_ad'           => 0,
					'referer'           => 'taobao订单下载',
					'consignee'     => $tb_trade['receiver_name'],  //收货人 
					'mobile'   => $tb_trade['receiver_mobile'],//手机
					'tel'      => $tb_trade['receiver_phone'], //电话 
					'email'    => $tb_trade['buyer_email'],//邮件
					'zipcode'  => $tb_trade['receiver_zip'],//邮编
					'address'  => $tb_trade['receiver_state'] .' '.$tb_trade['receiver_city'].' '.$tb_trade['receiver_district'].' ' .$tb_trade['receiver_address'],//收货人地址
					'country'   => 1, // 中国    
					'province'   => Check_is_exist('region','region_type','1',"region_name  like '%". str_replace_region($tb_trade['receiver_state'])."%' ",'region_id' ) , //  $tb_trade['receiver_state'];//省ID
					'city'   	 => Check_is_exist('region','region_type','2',"region_name  like '%". str_replace_region($tb_trade['receiver_city'])."%' ",'region_id' ) , //  $tb_trade['receiver_city'];//州/市ID
					'district'   => Check_is_exist('region','region_type','3',"region_name  like '%". str_replace_region($tb_trade['receiver_district'])."%' ",'region_id' ) , // $tb_trade['receiver_district'];//市县ID
 					'goods_count' => $tb_trade['num'], //购买商品数量
					'order_from'  => 8,  	//taobao网订单。来由  
					'to_buyer'    =>'交易号:'.$tb_trade['tid'].", 商家备注：(". $result['seller_memo'] .")"   ,//taobao上的订单号  //放入给商家流言字段中  
					'postscript'   => $result['buyer_message'] ,//订单附言，由用户提交订单前填写
					'goods_amount' =>$tb_trade['total_fee'],  //商品金额
					'orders_count' =>$tb_trade['num'],  //数量
					'shipping_fee' =>$tb_trade['post_fee'],  //运费 
					'pay_id'    => Check_is_exist('payment','pay_code','alipay','','pay_id') ,//支付宝ID 
					'pay_time'  => gmstr2time( $tb_trade['pay_time']  ) ,//支付时间
					'pay_name'  => '支付宝:'.$tb_trade['buyer_alipay_no'].'<br/>交易号:'.$tb_trade['alipay_no'],  //支付宝号交易号 
					'shipping_id' =>  $shipping_id,
					'shipping_name' => $shipping_company_name ,
					'invoice_no'  => $shipping_out_sid , 
				 );  		 
		if(!$shipping_id){  //系统自动关联快递公司
			    if($shipping_type =='ems'){
			    	$order['shipping_id'] =Check_is_exist('shipping','shipping_code',Check_is_exist('tb_shipping','company_code',"ems",'','field1') ,'',"shipping_id" ) ;
			    	$order['shipping_name'] =Check_is_exist('shipping','shipping_code',Check_is_exist('tb_shipping','company_code',"ems",'','field1') ,'',"shipping_name" ) ;
			    }elseif ($shipping_type =='post'){
			    	$order['shipping_id'] =Check_is_exist('shipping','shipping_code',Check_is_exist('tb_shipping','company_code',"post",'','field1') ,'',"shipping_id" ) ;
			    	$order['shipping_name'] =Check_is_exist('shipping','shipping_code',Check_is_exist('tb_shipping','company_code',"post",'','field1') ,'',"shipping_name" ) ;
			    }elseif ($shipping_type =='express') {
			     	$order['shipping_id'] = Check_is_exist('shipping','defalut_delivery','1','','shipping_id')	 ;  //不存在自动关联默认  快递ID
		 			$order['shipping_name'] = Check_is_exist('shipping','defalut_delivery','1','','shipping_name')	 ; //快递名称
	 			}
	 			if(!$order['shipping_id']){
	 				$order['shipping_id'] = Check_is_exist('shipping','defalut_delivery','1','','shipping_id')	 ;  //不存在自动关联默认  快递ID
		 			$order['shipping_name'] = Check_is_exist('shipping','defalut_delivery','1','','shipping_name')	 ; //快递名称
	 		 	 }
		}  
		$use_buss_desc = get_code_value(get_tb_settings(null),'use_buss_desc') ;  //得到是否启用商家备注
		$use_buss_desc_no  = get_code_value(get_tb_settings(null),'use_buss_desc_no') ; //没有备注。操作1转订单 2不转订单
		$use_buss_desc_no_lock = get_code_value(get_tb_settings(null),'use_buss_desc_no_lock') ; //没有备注。操作1转订单 2不转订单
		if( $use_buss_desc && (get_code_value(get_tb_settings(null),'lock_tag')) && (strstr($result['seller_memo'],get_code_value(get_tb_settings(null),'lock_tag'))) ) {
			// $order['process_status'] = 1;	//process_status  判断是否挂起	//写日志
		}else {  //未挂起 直接确认并减可用库存   减去可用库存 
			$order['order_status'] =1; //未挂起 则 系统自动确认并减可用库存 ;   
			/**** 到明细表中去 减可用库存:方法  下载明细时判断是否是已经自动确认的。如果是自动确认的则立即减可用库存    **/ 
		}  
		if( $use_buss_desc && $use_buss_desc_no_lock && $use_buss_desc_no_lock  ){  //如果启用商家备注 并 设置不备注操作
			$order['process_status'] = 1;	//process_status  判断是否挂起	//写日志
		}  
		$use_postscript = get_code_value(get_tb_settings(null),'use_postscript') ;  //use_postscript启用买家留言
		$use_postscript_have = get_code_value(get_tb_settings(null),'use_postscript_have') ;  //use_postscript_have已留言   1确认,2未确认
		$use_postscript_have_lock = get_code_value(get_tb_settings(null),'use_postscript_have_lock') ;  //use_postscript_have_lock有留言并挂起
		$use_postscript_no = get_code_value(get_tb_settings(null),'use_postscript_no') ; //use_postscript_no 未留言    1确认,2未确认	
		if($use_postscript  && $order['postscript'] ){ //启用买家留言 并留言存在
			//if($use_postscript_have_lock ) $order['process_status'] = 1; //挂起
			if($use_postscript_have==1){
				$order['order_status'] =1; //确认
			}else {
				$order['order_status'] =0; //未确认
			}
		}elseif ( $use_postscript &&  !$order['postscript']){	//启用买家留言 并留言不存在
			if($use_postscript_no==1) {  
				$order['order_status'] =1; //确认
			}else {
				$order['order_status'] =0; //未确认
			} 
		} 
		OS_InsertIntoTB('order_info','order_sn',$order);	 //更新或插入订单主表  可以在此加条件   
		if($use_postscript  && $order['postscript'] && $use_postscript_have_lock )  question_order($order_sn , 20, '启用买家留言 并留言存在并转问题') ; //问题单
		if($use_buss_desc && (get_code_value(get_tb_settings(null),'lock_tag')) && (strstr($result['seller_memo'],get_code_value(get_tb_settings(null),'lock_tag'))) )  question_order($order_sn , 20, '商家备注中符合问题单条件') ; //问题单
		Update_table_key('tb_trade','outer_order_sn',$order_sn,"tid='".$result['tid']."'");  //更新关联表的tb_trade表中outer_order_sn 
  		return Check_is_exist('order_info','order_sn',$order_sn,'','order_id')  ;  
	}  
	/**
	* 插入表order_goods
	*/
	function  InsertIntoOrder_goods($result,$order_id ){  
		 global  $db,$os ;
		  if(is_array($result['orders']) && is_array($result['orders']['order']) && $result['orders']['order'][0] ) {   
		 		$real_list=$result['orders']['order'];
		 }elseif (is_array($result['orders'])) {
		 	    $real_list[0]=$result['orders']['order']; 
		 }
		foreach( $real_list AS $list) { 
				$iid = $list['iid']; 	//商品iid
				$sku_id = $list['sku_id']; 
				if(!Check_is_exist('tb_item','iid',$iid)) GetTBOneItem( $iid ) ;  //此商品本地数据库中没有,未下载则先下载商品 
				if($sku_id && !Check_is_exist('tb_sku','sku_id',$sku_id) ) GetInsertIntoSKU( $sku_id ); //如果sku不在本地数据表则再次请求
			 	$sql="select num_iid,title,cid,property_alias,goods_id,goods_sn from ". $os->table('tb_item') ." left join ". $os->table('goods') ."  on outer_id=goods_sn
					  where iid='$iid' ";   //得到goods_id   
			    $goods_row = $db->getRow($sql); 
			    if(!$goods_sn =$goods_row['goods_sn']) {
			    	echo ('宝贝:'.$iid.'['.$goods_row['num_iid'].']'.$goods_row['title'].'  未关联起来,请手工关联商品!<br/>'.$sql) ; 
			    	return ;
			    }
				$goods_id =$goods_row['goods_id']  ;  
				$cid = $goods_row['cid']  ;  
			    $property_alias =$goods_row['property_alias']  ;  
			    if( $sku_id ){ //说明颜色尺码存在 
					$properties= $db->getOne("select properties from open_tb_sku where sku_id='".$sku_id."'")  ; //得到SKU中的属性 	
 					$guige_arr = getGuigeByProperties( $properties ,$cid,$goods_sn) ;
					$color_id = $guige_arr['color_id'] ;
					$size_id = $guige_arr['size_id']  ; 
			    }else { //不存在sku
			    	keepguige();//得到000 GetUnicolor()
					if(!$color_id) $color_id = Check_is_exist('color','color_code',GetUnicolor(),'','color_id');
					if(!$size_id)  $size_id = Check_is_exist('size','size_code',GetUnisize(),'','size_id'); 
			    }  
			    $order_goods =array(
			    			'order_id' => $order_id ,
			    			'goods_id' => $goods_id,
			    			'goods_name' =>$list['title'] ,
			    			'goods_sn' =>  $goods_sn,
			    			'goods_number' => $list['num'] ,
			    			'market_price' => Check_is_exist('goods','goods_id',$goods_id,'','shop_price') ,  
			    			'goods_price' => $list['price'],	
			    			'goods_attr' => str_replace(";","<br/>",$list['sku_properties_name']) ,
			    			'color_id' =>$color_id ,	
			    			'size_id' => $size_id,	
			    			'is_real' =>'1',
			    			'parent_id' =>'0',
			    			'is_gift' =>'0',
			    			'is_rejected' =>'0',		
			    		);  		
			   OS_InsertIntoTB('order_goods','order_id',$order_goods,"goods_id ='".$goods_id."' and color_id ='".$color_id."' and size_id='".$size_id."'"); 		
		  } 
	  }   
	/**
	 *  根据  $properties $cid $goods_sn 得到  $color_id $size_id
	 * */
	function getGuigeByProperties($properties,$cid,$goods_sn){
		global  $db,$os ;
		if( $properties ){  //颜色尺码 
				$guiges = explode(';', $properties );   
				$guige1= explode(':',$guiges[0] )  ;  //颜色:白色 
				$vid = $guige1[1] ; 
				if($vid){
					$sql= "select c.color_id from open_tb_guige1 as tb_gg1 left join open_color as c on tb_gg1.color_code=c.color_code where tb_gg1.cid='".$cid."' and tb_gg1.vid='".$vid."'";
					/* and tb_gg1.spdm='".$goods_sn."' " ;*/  //去掉商品代码，flying.liu  2010.04.07
					if( !$color_id = $db->getOne($sql) ) {   
						AutoExeGuige($goods_sn,$property_alias,$cid);
						$sql= "select c.color_id from open_tb_guige1 as tb_gg1 left join open_color as c on tb_gg1.color_code=c.color_code where tb_gg1.cid='".$cid."' and tb_gg1.vid='".$vid."'  and tb_gg1.spdm='".$goods_sn."' " ;
						if( !$color_id = $db->getOne($sql)  ) {
							echo ('商品['.$goods_sn.']颜色仍未关联'. $sql .$property_alias. '<br/>请手工关联!<br/><a href="#" onclick="history.go(-1)">返回</a>' ) ; 
							return ;
						}
				    } 	
				}else {
					if(!$color_id=Check_is_exist('color','color_code',GetUnicolor(),'','color_id')) keepguige();
					if(!$color_id) $color_id = Check_is_exist('color','color_code',GetUnisize(),'','color_id');
				}  
				$guige2= explode(':',$guiges[1])  ;  //尺码
				$vid = $guige2[1] ; 
				if($vid ){
					$sql= "select s.size_id from open_tb_guige2 as tb_gg2 left join open_size as s on tb_gg2.size_code=s.size_code where tb_gg2.cid='".$cid."' and tb_gg2.vid='".$vid."'";
						// and tb_gg2.spdm='".$goods_sn."' " ; //去掉商品代码，flying.liu  2010.04.07
					    if(  !$size_id = $db->getOne($sql) ) {  
						    AutoExeGuige($goods_sn,$property_alias,$cid);
							$sql= "select s.size_id from open_tb_guige2 as tb_gg2 left join open_size as s on tb_gg2.size_code=s.size_code where tb_gg2.cid='".$cid."' and tb_gg2.vid='".$vid."' and tb_gg2.spdm='".$goods_sn."'" ;
						    if(  !$size_id = $db->getOne($sql)  ) {
								echo ('商品['.$goods_sn.']尺码仍未关联'. $sql .$property_alias.'<br/>请手工关联!<br/><a href="#" onclick="history.go(-1)">返回</a>' ) ;
								return ;
							}
						}
				}else {
				if(!$size_id=Check_is_exist('size','size_code',GetUnicolor(),'','size_id')) keepguige();
					if(!$size_id) $size_id=Check_is_exist('size','size_code',GetUnisize(),'','size_id'); 
				} 
			}else { //不存在 默认颜色尺码 
				keepguige();//得到000 
				if(!$color_id) $color_id = Check_is_exist('color','color_code',GetUnicolor(),'','color_id');
				if(!$size_id)  $size_id = Check_is_exist('size','size_code',GetUnisize(),'','size_id'); 
			} 
			$guige_arr = array(
							'color_id' =>$color_id,
							'size_id' =>$size_id ,
						);	
		    return $guige_arr; 
	}
?>
